package com.server.file.controller;

import com.server.file.constants.CommonConstants;
import com.server.file.dto.Result;
import com.server.file.model.DataFile;
import com.server.file.service.DataFileService;
import com.server.file.support.FastDFSClientWrapper;
import com.server.file.util.ByteUploadDto;
import com.server.file.util.ResponseInfo;
import com.server.file.util.ResponseUtil;
import com.server.file.utils.BusinessUtil;
import com.server.file.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * @author ygl
 * @create 2018-06-04
 * @DESCRIPTION
 **/
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FastDFSClientWrapper dfsClient;

    @Autowired
    private DataFileService dataFileService;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file, ServletRequest request) {
        String path = null;
        try {
            path = dfsClient.getPathUrl(dfsClient.uploadFile(file));
            // 上传成功后保存文件记录
            DataFile ds = new DataFile();
            int source = CommonConstants.SOURCE_IM;
            Map<String, String[]> params = request.getParameterMap();
            if(params.size() > 0) {
                ds.setPatientId(Long.valueOf(params.get("patientId")[0].toString()));
                ds.setComplaintId(Long.valueOf(params.get("complaintId")[0].toString()));
                ds.setType(Integer.valueOf(params.get("type")[0].toString()));
                ds.setAccountId(Long.valueOf(params.get("accountId")[0]));
                ds.setOrganId(Long.valueOf(params.get("organId")[0]));
                ds.setOrganName(params.get("organName")[0].toString());
                source = CommonConstants.SOURCE_SYSTEM;
            }
            ds.setSource(source);
            ds.setName(file.getOriginalFilename());
            ds.setPath(path);
            ds.setSize(file.getSize());
            try{
                BufferedImage image = ImageIO.read(file.getInputStream());
                if(image != null){
                    ds.setWidth(image.getWidth(null));
                    ds.setHeight(image.getHeight(null));
                }
            }catch (Exception e){
            }
            BusinessUtil.appendRecord(ds);
            dataFileService.doSave(ds);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultUtil.success();
    }


    @PostMapping("/byte/upload")
    public ResponseInfo upload(@RequestBody ByteUploadDto uploadDto) {
        byte[] bytes = uploadDto.getBytes();
        if (bytes == null) {
            ResponseUtil.ERROR("字节数据为空");
        }
        String fileExtension = uploadDto.getFileExtension();
        if (StringUtils.isEmpty(fileExtension)) {
            ResponseUtil.ERROR("字节数据为空");
        }
        String url;
        try {
            url = dfsClient.uploadFile(bytes, fileExtension);
            return ResponseUtil.OK(dfsClient.getPathUrl(url));
        } catch (Exception e) {
            return ResponseUtil.ERROR(e.getMessage());
        }
    }

    @PostMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response){
        ServletOutputStream out = null;
        try{
            Long id = Long.valueOf(request.getParameter("id"));
            DataFile ds = dataFileService.findOne(id);
            if(ds != null){
                URL url = new URL(ds.getPath());
                InputStream inputStream = url.openStream();
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=" + ds.getName());
                out = response.getOutputStream();
                int byteread = 0;
                byte[] buffer = new byte[1024];
                while ((byteread = inputStream.read(buffer)) != -1) {
                    // 4.写到输出流(out)中
                    out.write(buffer, 0, byteread);
                }
                inputStream.close();
                out.flush();
                out.close();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody List<Long> ids){
        return dataFileService.doDelete(ids);
    }
}